import { Component, OnInit } from '@angular/core';
import { CrawlerPage, ICrawlerPage } from '../shared/model/crawler-page.model';
import { HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CrawlerPageService } from '../entities/crawler-page/crawler-page.service';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';

@Component({
  selector: 'jhi-upload-page',
  templateUrl: './upload-page.component.html',
  styleUrls: ['./upload-page.component.scss'],
})
export class UploadPageComponent implements OnInit {
  private fileList: NzUploadFile[] = [];
  private isSaving = false;
  constructor(protected iCrawlerPage: CrawlerPageService) {}

  ngOnInit(): void {}
  handleChange({ file, fileList }: NzUploadChangeParam): void {
    this.fileList = fileList;
  }
  upload(): void {
    this.fileList.forEach(f => {
      if (f.originFileObj instanceof File) {
        f.originFileObj.text().then(e => {
          debugger;
          const crawlerPage: CrawlerPage = Object.assign(new CrawlerPage(), JSON.parse(e));
          this.subscribeToSaveResponse(this.iCrawlerPage.create(crawlerPage));
        });
      }
    });
  }
  protected subscribeToSaveResponse(result: Observable<HttpResponse<ICrawlerPage>>): void {
    result.subscribe(
      () => this.onSaveSuccess(),
      () => this.onSaveError()
    );
  }
  protected onSaveSuccess(): void {
    this.isSaving = false;
  }

  protected onSaveError(): void {
    this.isSaving = false;
  }
}
